import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Plus, Edit, Trash2, Server } from "lucide-react";
import { insertBackendServerSchema, BackendServer } from "@shared/schema";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { z } from "zod";

const formSchema = insertBackendServerSchema.extend({
  status: z.enum(["healthy", "unhealthy", "disabled"]),
});

type FormData = z.infer<typeof formSchema>;

export default function ServerManagement() {
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingServer, setEditingServer] = useState<BackendServer | null>(null);
  const { toast } = useToast();

  const { data: proxyRules = [] } = useQuery({
    queryKey: ["/api/proxy-rules"],
  });

  const { data: backendServers = [], isLoading } = useQuery({
    queryKey: ["/api/backend-servers"],
  });

  const {
    register,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      proxyRuleId: 0,
      host: "localhost",
      port: 8080,
      weight: 1,
      status: "healthy",
      responseTime: 0,
    },
  });

  const createServerMutation = useMutation({
    mutationFn: (data: FormData) => apiRequest("POST", "/api/backend-servers", data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/backend-servers"] });
      toast({ title: "后端服务器添加成功" });
      reset();
      setIsFormOpen(false);
    },
    onError: () => {
      toast({ title: "添加失败", variant: "destructive" });
    },
  });

  const updateServerMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<FormData> }) => 
      apiRequest("PUT", `/api/backend-servers/${id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/backend-servers"] });
      toast({ title: "后端服务器更新成功" });
      reset();
      setIsFormOpen(false);
      setEditingServer(null);
    },
    onError: () => {
      toast({ title: "更新失败", variant: "destructive" });
    },
  });

  const deleteServerMutation = useMutation({
    mutationFn: (id: number) => apiRequest("DELETE", `/api/backend-servers/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/backend-servers"] });
      toast({ title: "后端服务器删除成功" });
    },
    onError: () => {
      toast({ title: "删除失败", variant: "destructive" });
    },
  });

  const onSubmit = (data: FormData) => {
    if (editingServer) {
      updateServerMutation.mutate({ id: editingServer.id, data });
    } else {
      createServerMutation.mutate(data);
    }
  };

  const handleEdit = (server: BackendServer) => {
    setEditingServer(server);
    setValue("proxyRuleId", server.proxyRuleId);
    setValue("host", server.host);
    setValue("port", server.port);
    setValue("weight", server.weight || 1);
    setValue("status", server.status as "healthy" | "unhealthy" | "disabled");
    setIsFormOpen(true);
  };

  const handleCancel = () => {
    reset();
    setEditingServer(null);
    setIsFormOpen(false);
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'healthy':
        return (
          <Badge className="bg-green-100 text-green-800 hover:bg-green-100">
            <div className="w-2 h-2 bg-green-500 rounded-full mr-2"></div>
            健康
          </Badge>
        );
      case 'unhealthy':
        return (
          <Badge className="bg-red-100 text-red-800 hover:bg-red-100">
            <div className="w-2 h-2 bg-red-500 rounded-full mr-2"></div>
            异常
          </Badge>
        );
      case 'disabled':
        return (
          <Badge variant="secondary">
            <div className="w-2 h-2 bg-gray-500 rounded-full mr-2"></div>
            禁用
          </Badge>
        );
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

  const getProxyRuleName = (proxyRuleId: number) => {
    const rule = proxyRules.find((r: any) => r.id === proxyRuleId);
    return rule?.name || "未知";
  };

  return (
    <div className="flex-1 overflow-hidden">
      {/* Header */}
      <header className="bg-white border-b border-slate-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-semibold text-slate-800">服务器管理</h2>
            <p className="text-slate-600">管理后端服务器和健康状态监控</p>
          </div>
          <Button 
            onClick={() => setIsFormOpen(true)}
            className="bg-primary hover:bg-blue-700"
          >
            <Plus className="w-4 h-4 mr-2" />
            添加服务器
          </Button>
        </div>
      </header>

      <div className="p-6 overflow-y-auto h-full space-y-6">
        {/* Server Form */}
        {isFormOpen && (
          <Card>
            <CardHeader>
              <CardTitle>
                {editingServer ? "编辑后端服务器" : "添加后端服务器"}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-2">
                    <Label htmlFor="proxyRuleId">关联代理规则 *</Label>
                    <Select 
                      value={watch("proxyRuleId")?.toString()} 
                      onValueChange={(value) => setValue("proxyRuleId", parseInt(value))}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择代理规则" />
                      </SelectTrigger>
                      <SelectContent>
                        {proxyRules.map((rule: any) => (
                          <SelectItem key={rule.id} value={rule.id.toString()}>
                            {rule.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    {errors.proxyRuleId && (
                      <p className="text-sm text-red-600">{errors.proxyRuleId.message}</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="host">服务器地址 *</Label>
                    <Input
                      id="host"
                      placeholder="localhost"
                      {...register("host")}
                    />
                    {errors.host && (
                      <p className="text-sm text-red-600">{errors.host.message}</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="port">端口 *</Label>
                    <Input
                      id="port"
                      type="number"
                      placeholder="8080"
                      {...register("port", { valueAsNumber: true })}
                    />
                    {errors.port && (
                      <p className="text-sm text-red-600">{errors.port.message}</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="weight">权重</Label>
                    <Input
                      id="weight"
                      type="number"
                      placeholder="1"
                      {...register("weight", { valueAsNumber: true })}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="status">状态</Label>
                    <Select 
                      value={watch("status")} 
                      onValueChange={(value) => setValue("status", value as "healthy" | "unhealthy" | "disabled")}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="healthy">健康</SelectItem>
                        <SelectItem value="unhealthy">异常</SelectItem>
                        <SelectItem value="disabled">禁用</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="flex items-center justify-end space-x-4">
                  <Button type="button" variant="outline" onClick={handleCancel}>
                    取消
                  </Button>
                  <Button 
                    type="submit" 
                    disabled={createServerMutation.isPending || updateServerMutation.isPending}
                    className="bg-primary hover:bg-blue-700"
                  >
                    {editingServer ? "更新" : "添加"}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        )}

        {/* Servers Table */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-lg font-semibold text-slate-800">后端服务器列表</CardTitle>
                <p className="text-slate-600 text-sm">管理和监控后端服务器状态</p>
              </div>
              <div className="flex items-center space-x-2">
                <Server className="w-5 h-5 text-slate-500" />
                <span className="text-sm text-slate-600">
                  {backendServers.length} 台服务器
                </span>
              </div>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-slate-50">
                    <TableHead className="font-medium text-slate-600">代理规则</TableHead>
                    <TableHead className="font-medium text-slate-600">服务器地址</TableHead>
                    <TableHead className="font-medium text-slate-600">端口</TableHead>
                    <TableHead className="font-medium text-slate-600">权重</TableHead>
                    <TableHead className="font-medium text-slate-600">状态</TableHead>
                    <TableHead className="font-medium text-slate-600">响应时间</TableHead>
                    <TableHead className="font-medium text-slate-600">最后检查</TableHead>
                    <TableHead className="font-medium text-slate-600">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {isLoading ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-8">
                        加载中...
                      </TableCell>
                    </TableRow>
                  ) : backendServers.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-8 text-slate-500">
                        暂无后端服务器，请添加新服务器
                      </TableCell>
                    </TableRow>
                  ) : (
                    backendServers.map((server: BackendServer) => (
                      <TableRow key={server.id} className="hover:bg-slate-50">
                        <TableCell>
                          <div className="font-medium text-slate-800">
                            {getProxyRuleName(server.proxyRuleId)}
                          </div>
                        </TableCell>
                        <TableCell className="text-slate-600">{server.host}</TableCell>
                        <TableCell className="text-slate-600">{server.port}</TableCell>
                        <TableCell className="text-slate-600">{server.weight}</TableCell>
                        <TableCell>{getStatusBadge(server.status)}</TableCell>
                        <TableCell className="text-slate-600">
                          {server.responseTime ? `${server.responseTime}ms` : '-'}
                        </TableCell>
                        <TableCell className="text-slate-600">
                          {server.lastHealthCheck 
                            ? new Date(server.lastHealthCheck).toLocaleString('zh-CN')
                            : '-'
                          }
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center space-x-2">
                            <Button 
                              size="sm" 
                              variant="ghost"
                              onClick={() => handleEdit(server)}
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button 
                              size="sm" 
                              variant="ghost"
                              onClick={() => deleteServerMutation.mutate(server.id)}
                              disabled={deleteServerMutation.isPending}
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
